package controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.bean.Account;
import model.bo.AccountSettingBO;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

import common.Privilege;

/**
 * Servlet implementation class AccountSettingServlet
 */
public class AccountSettingServlet extends HttpServlet {

    public AccountSettingServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	    response.setCharacterEncoding("UTF-8");
	    request.setCharacterEncoding("UTF-8");
	    
		String action = (String) request.getParameter("action").trim();
		
		AccountSettingBO accountSettingBO = new AccountSettingBO();
		HttpSession session = request.getSession();
		Account account = (Account) session.getAttribute("account");
		
		String folder = "";
		switch (account.getPrivilege()) {
            case Privilege.ADMIN:
                folder = "administrator/";
                break;
            case Privilege.MANAGE_TOUR:
                folder = "manage_tour/";
                break;
            case Privilege.MANAGE_SERVICE:
                folder = "manage_service/";            
                break;
            case Privilege.MANAGE_NEWS:
                folder = "manage_news/";
                break;
            case Privilege.MANAGE_TRANSACTION:
                folder = "customer_service/";
                break;
        }
		
		
		if ("changePassword".equals(action)) {
			
			String password = (String) request.getParameter("password");
			String oldpassword = (String) request.getParameter("oldpassword");
			
			if( !oldpassword.equals(account.getPassword())) {
				request.setAttribute("errMessage", "The Old password isn't correct");
				RequestDispatcher rd = request.getRequestDispatcher(folder+ "changepass.jsp");
				rd.forward(request, response);
			}else {
				if( accountSettingBO.updatePassword(account,password) > 0){
					request.setAttribute("errMessage", "Password was changed sussesfully");
				}else{
					request.setAttribute("errMessage", "Update password have an error");
				}
				RequestDispatcher rd = request.getRequestDispatcher(folder+  "changepass.jsp");
				rd.forward(request, response);
			}
		}else if("updateInfo".equals(action)) {
			
			Account acc = new Account();
			acc.setNameAccount(account.getNameAccount());   // Note here
			HashMap<String, String> listParamet = new HashMap<String, String>();
			String fileAvatar = "";
			InputStream contentAvatar = null;
			try {
				  	DiskFileItemFactory factory = new DiskFileItemFactory();
			        List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
			        for (FileItem item : items) {
			            if (item.isFormField()) {
			            	// Process form field: radio, select, checkbox ...
			            	listParamet.put(item.getFieldName(), item.getString("UTF-8"));
			            } else {
			                fileAvatar = FilenameUtils.getName(item.getName());
			                contentAvatar = item.getInputStream();
			            }
			        }
			        acc.setName(listParamet.get("fullName"));
			        acc.setSex(Boolean.parseBoolean(listParamet.get("gender")));
			        acc.setEmail(listParamet.get("email"));
			        acc.setPhoneNumber(listParamet.get("phone"));
			        acc.setDateOfBirth(listParamet.get("dob"));
			       
			 } catch (FileUploadException e) {
			        throw new ServletException("Cannot parse multipart request.", e);
			        
			 }
			if( accountSettingBO.updateInfoAccount(acc,fileAvatar,contentAvatar) > 0){
				request.setAttribute("errMessage", "Infomation was changed sussesfully");
				acc = accountSettingBO.getAccount(account.getNameAccount());
				if(acc != null){
					session.setAttribute("account", acc);
				}else{
				}
			} else {
				request.setAttribute("errMessage", "Update infomation account have an error");
			}
			RequestDispatcher rd = request.getRequestDispatcher( folder + "profile.jsp");
			rd.forward(request, response);
		}
	}
}
